<template>
    <el-dialog
        :title="dataForm.id ? '修改' : '新增'"
        width="40%"
        :visible="dialogVisible"
        :destroy-on-close="true"
        :modal-append-to-body="true"
        :before-close="handleClose"
    >
        <el-form
            ref="dataFormMenu"
            class="menu-dialog-cls"
            :model="dataForm"
            :rules="dataFormRules"
            label-width="100px"
            :size="size"
            style="text-align: left"
            @keyup.enter.native="submitForm()"
        >
            <slot />
            <FormTemplate :dataFormConfig="dataFormConfig" :dataFormMenu="dataForm" :editTag="editTag">
                <template slot="appId">
                    <el-select
                        v-model="dataForm.appId"
                        placeholder="请选择应用"
                        @change="handleAppId"
                        :disabled="editTag === 'edit' || editTag === 'menu'"
                    >
                        <el-option
                            v-for="item in appManagerData"
                            :key="item.id"
                            :label="item.appName"
                            :value="item.id"
                        ></el-option>
                    </el-select>
                </template>
                <template slot="icon" v-if="type == 1 || type == 2">
                    <IconPicker v-model="dataForm.icon" />
                </template>
                <template slot="parentId" v-if="type == 2 || type == 3">
                    <TreeSelect
                        :disabled="editTag === 'edit' || editTag === 'menu'"
                        v-model="dataForm.parentId"
                        placeholder="请选择当前模块"
                        :defaultExpandAll="true"
                        :treeOptions="menuList"
                        :treeProps="deptTreeProps"
                        @getNodeData="getDeptNode"
                    ></TreeSelect>
                </template>
                <template slot="url">
                    <el-row>
                        <el-col :span="22">
                            <el-input v-model="dataForm.url" placeholder="菜单路由" />
                        </el-col>
                        <el-col :span="2" class="icon-list__tips">
                            <el-tooltip placement="top" effect="light" style="padding: 10px">
                                <div slot="content">
                                    <p>URL格式：</p>
                                    <p>访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头</p>
                                </div>
                                <i class="el-icon-warning" />
                            </el-tooltip>
                        </el-col>
                    </el-row>
                </template>
                <template slot="resourceCode">
                    <el-input
                        placeholder="请输入资源编码"
                        v-model="dataForm.resourceCode"
                        type="number"
                        :min="0"
                        v-if="editTag === 'add' || editTag === 'menu'"
                        oninput="if(value.length>3)value=value.slice(0,3)"
                    >
                        <template slot="prepend">
                            {{ codeBefore[type - 1].before }}{{ checkMenu.resourceCode }}
                        </template>
                    </el-input>
                    <el-input
                        :disabled="editTag == 'edit'"
                        v-if="editTag === 'edit'"
                        v-model="dataForm.resourceCode"
                        placeholder="请输入资源编码"
                    />
                </template>
            </FormTemplate>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :size="size" @click.native="closeDialog">取消</el-button>
            <el-button :size="size" type="primary" @click="submitForm()">确定</el-button>
        </span>
    </el-dialog>
</template>
<script>
//  :disabled="editTag === 'edit'"
// 类型（1-目录、2-菜单、3-按钮、4-API、5-数据、0-其它）'

import PopupTreeInput from '@/components/PopupTreeInput'
import IconPicker from '@/components/IconPicker/IconPicker'
import { findMenuTree } from '@/api/system/menu'
import { dialogVisible } from '@/mixins/dialogMixin'
import { appManagerPageList } from '@/api/system/application'
import { addRes, editRes, getParentResList } from '@/api/system/menu'
import TreeSelect from '@/components/TreeSelect'
import FormTemplate from './FormTemplate.vue'
import { validURL } from '@/utils/validate'
export default {
    components: {
        PopupTreeInput,
        IconPicker,
        TreeSelect,
        FormTemplate
    },
    props: {
        dataForm: {
            type: Object,
            default: () => {}
        },
        editTag: {
            type: String,
            default: 'add'
        },
        appManagerData: {
            type: Array,
            default: () => []
        },
        type: {
            type: Number,
            default: 1
        }
    },
    mixins: [dialogVisible],
    data() {
        var newUrl = (rule, value, callback) => {
            console.log('this.islink', this.isLink)
            console.log(value)
            if (this.type == 1) {
                callback(new Error('请填写模块'))
            } else {
                callback(new Error('请填写菜单路由'))
            }
        }
        return {
            size: 'small',
            loading: true,
            popupTreeProps: {
                label: 'name',
                children: 'children'
            },
            isLink: false,
            popupTreeData: [],
            dataFormRules: {
                appId: [{ required: true, message: '请选择应用名称', trigger: 'blur' }],
                resourceName: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    {
                        min: 2,
                        max: 10,
                        message: '长度在 2 到 10个字符',
                        trigger: 'blur'
                    }
                ],
                url: [{ required: true, message: '请填写路由', trigger: 'blur' }],
                parentId: [{ required: true, message: '请选择上级菜单', trigger: 'blur' }],
                resourceCode: [{ required: true, message: '资源编码必填', trigger: 'blur' }]
            },
            deptTreeProps: {
                value: 'id',
                label: 'resourceName',
                children: 'children'
            },
            //  模块
            dataFormConfig1: [
                { label: '模块名称', code: 'resourceName', type: 'input' },
                { label: '应用', code: 'appId', slot: 'appId' },
                { label: '资源编码', code: 'resourceCode', slot: 'resourceCode' },
                { label: '菜单路由', code: 'url', slot: 'url' },
                { label: '菜单图标', code: 'icon', slot: 'icon' },
                { label: '描述', code: 'description', type: 'textarea' }
            ],
            // 菜单
            dataFormConfig2: [
                { label: '菜单名称', code: 'resourceName', type: 'input' },
                { label: '应用', code: 'appId', slot: 'appId' },
                { label: '当前模块', code: 'parentId', slot: 'parentId' },
                { label: '资源编码', code: 'resourceCode', slot: 'resourceCode' },
                { label: '菜单路由', code: 'url', slot: 'url' },
                { label: '图标', code: 'icon', slot: 'icon' },
                { label: '描述', code: 'description', type: 'textarea' }
            ],
            // 按钮
            dataFormConfig3: [
                { label: '按钮名称', code: 'resourceName', type: 'input' },
                { label: '应用', code: 'appId', slot: 'appId' },
                {
                    label: '上级菜单',
                    code: 'parentId',
                    slot: 'parentId',
                    disabled: true
                },
                { label: '资源编码', code: 'resourceCode', slot: 'resourceCode' },
                { label: '授权标识', code: 'perms', type: 'input' },
                { label: '描述', code: 'description', type: 'textarea' }
            ],
            // api
            dataFormConfig: [],
            menuList: [],
            // 根据应用选出来的上级菜单
            checkMenu: {},
            // 资源code前缀定义
            codeBefore: [
                {
                    before: 'O',
                    code: ''
                },
                {
                    before: 'T',
                    code: ''
                },
                {
                    before: 'S',
                    code: ''
                }
            ],
            resourceHierarchy: 1
        }
    },
    created() {
        if (this.editTag == 'menu') {
            this.getDeptNode(this.dataForm)
        }
    },
    mounted() {
        this.dataFormConfig = this.dataFormConfig0
        this.$nextTick(() => {
            this.handleRadio(this.type)
        })
    },
    watch: {
        editTag: function () {
            if (this.editTag == 'menu') {
                this.getDeptNode(this.dataForm)
            }
        }
    },
    methods: {
        // 选择菜单时的入菜处理
        getDeptNode(row) {
            const { type } = this
            const { resourceHierarchy, resourceCode } = row
            console.log('getDeptNode', row)
            // 修改层级
            this.resourceHierarchy = resourceHierarchy + 1
            //resourceCode 码
            if (type == '2' || type == '3') {
                this.codeBefore[type - 1].code = resourceCode.substring(1, 6)
                this.checkMenu = Object.assign(
                    {},
                    {
                        resourceCode: resourceCode.substring(1, 6)
                    }
                )
            } else {
                this.checkMenu = row
            }
        },
        // 获取上级菜单树
        getParentMenuTree(tableTreeDdata) {
            let parent = {
                parentId: 0,
                name: '顶级菜单',
                children: tableTreeDdata
            }
            return [parent]
        },
        // 菜单树选中
        handleTreeSelectChange(data, node) {
            this.dataForm.parentId = data.id
            this.dataForm.parentName = data.name
        },
        handleRadio(type) {
            if (type == 1) {
                this.dataFormConfig = this.dataFormConfig1
            } else if (type == 2) {
                this.dataFormConfig = this.dataFormConfig2
            } else {
                this.dataFormConfig = this.dataFormConfig3
            }
            this.$nextTick(() => {
                this.$refs['dataFormMenu'].clearValidate()
                this.$refs.dataFormMenu.resetFields()
            })
        },

        // 选中应用  去拉取应用下面的菜单
        handleAppId(val) {
            const { type } = this
            if (type === 1) return
            const params = {
                appId: val,
                type
            }
            getParentResList(params).then((res) => {
                console.log(res)
                this.menuList = res.data
            })
        },
        // 表单提交
        submitForm() {
            let fetchApi = ''
            if (this.editTag === 'add' || this.editTag === 'menu') {
                fetchApi = addRes
            } else {
                fetchApi = editRes
            }
            const { resourceCode } = this.dataForm
            const { type, resourceHierarchy } = this
            this.$refs['dataFormMenu'].validate((valid) => {
                if (valid) {
                    this.$confirm('确认提交吗？', '提示', {}).then(() => {
                        let params = {}
                        if (this.editTag == 'add' || this.editTag == 'menu') {
                            params = Object.assign({}, this.dataForm, {
                                resourceCode:
                                    this.codeBefore[type - 1].before + this.codeBefore[type - 1].code + resourceCode,
                                type: type,
                                resourceHierarchy
                            })
                            console.log('add.pransm', params)
                        } else {
                            params = Object.assign({}, this.dataForm, {
                                type: type,
                                resourceHierarchy
                            })
                        }
                        console.log('入参-----》', params)
                        fetchApi(params).then((res) => {
                            if (res.code == 200) {
                                this.$message({ message: '操作成功', type: 'success' })
                                this.$refs['dataFormMenu'].resetFields()
                                this.closeDialog()
                                this.$emit('getPageList')
                            } else {
                                this.$message({
                                    message: '操作失败, ' + res.msg,
                                    type: 'error'
                                })
                            }
                        })
                    })
                }
            })
        }
    }
}
</script>
<style lang="scss">
.menu-dialog-cls {
    padding-right: 35px;
    .el-form-item__label {
        width: 17% !important;
    }
    .el-form-item__content {
        margin-left: 18% !important;
        margin-right: 0.5% !important;
    }
    .el-textarea__inner {
        min-height: 120px !important;
    }
}
</style>
